package org.ar.tiendaonline.persistence;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.ar.tiendaonline.vo.Factura;

public class FacturaHibernateDao implements FacturaDao{
	
	private List<Factura> facList;
	private Factura fac;
	
	
	public List getAllFacturas() {
		Session session = HibernateUtil.getSession();
		
		try {
			session.beginTransaction();
			facList = session.createQuery(
					"from Factura as f left join fetch f.proveedor p").list();
			return facList;
		} finally {
			session.close();
		}
	}
	
	
	public Factura getFactura(Integer id) {
			Session session = HibernateUtil.getSession();
			
			try{
				session.beginTransaction();
				Query q = session
							.createQuery("from Factura as f inner join fetch f.proveedor d where f.facturaId =:facturaId");
				q.setInteger("facturaId", id);
				return (Factura) q.uniqueResult();
			} finally {
				session.close();
			}
	}
	
	
	public void insert(Factura fac) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		
		try {
			tx = session.beginTransaction();
			session.save(fac);
			tx.commit();
		} catch (RuntimeException e) {
			if(tx != null) tx.rollback();
			throw e;
		} finally {
			session.close();
		}
		
	}
	
	
	public void update(Factura fac) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx=session.beginTransaction();
			session.update(fac);
			tx.commit();
		}catch (RuntimeException e) {
			if(tx != null) tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
	
	
	public void delete(Integer id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			fac = (Factura)session.get(Factura.class, id);
			session.delete(fac);
			tx.commit();
		} catch (RuntimeException e) {
			if(tx != null) tx.rollback();
			throw e;
		} finally {
		    session.close();
			}   
	}

}
